package com.crazymakercircle.demo.zbl.juc;

import com.crazymakercircle.util.Print;
import com.crazymakercircle.util.ThreadUtil;
import org.junit.Test;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicInteger;

public class AtomicTest {

    @Test
    public  void atomicIntegerTest(){
        int tempValue=0;

        AtomicInteger i = new AtomicInteger(tempValue);

        // 取值并设置新值
        int andAdd = i.getAndAdd(3);
        Print.fo("取值="+andAdd+"设置的新值="+i.get());

        // 取值 然后自增
        int andIncrement = i.getAndIncrement();
        Print.fo("取值="+andIncrement+" 自增后的值="+i.get());

        // 取值然后增加
        int andAdd1 = i.getAndAdd(5);
        Print.fo("取值="+andAdd1+" 增加后的值="+i.get());

        // cas操作
        boolean b = i.compareAndSet(9, 100);
        Print.fo("cas结果：b"+" cas后的结果值："+i.get());
    }

    @Test
    public  void add1000Test() throws InterruptedException {
        CountDownLatch countDownLatch = new CountDownLatch(10);
        AtomicInteger atomicInteger = new AtomicInteger(0);

        for (int i=0;i<10;i++){

            ThreadUtil.getMixedTargetThreadPool().submit(()->{
               for(int j=0;j<1000;j++){
                   atomicInteger.getAndIncrement();
               }
               countDownLatch.countDown();
            });
        }
        countDownLatch.await();
        Print.fo("累计之和："+atomicInteger.get());
    }
}
